import { ValueStore } from "maishu-chitu-service";
import { WeiXinSetting, User } from 'entities';
import { Service, stationPath } from "common/static/index";
import { DataSourceSelectArguments, DataSourceSelectResult } from "maishu-wuzhui";

interface LoginResult {
    token: string
}

export class WeiXinService extends Service {

    static token = new ValueStore();

    url(path) {
        return stationPath(path);
    }

    //======================================================
    // Setting
    getSetting() {
        let url = this.url('setting/item');
        return this.get<WeiXinSetting>(url);
    }
    saveSetting(setting: WeiXinSetting) {
        let url = this.url('setting/set');
        return this.putByJson(url, { item: setting });
    }
    //======================================================

    //======================================================
    // User
    async userList(args: DataSourceSelectArguments) {
        let url = this.url("user/list");
        let r = await this.getByJson<DataSourceSelectResult<User>>(url, { args });
        return r;
    }
    //======================================================


    getMessageTemplateTypes() {
        let url = this.url('WeiXin/GetMessageTemplateTypes');
        return this.get<any[]>(url);
    }
    openId(code: string): Promise<string> {
        let url = this.url('WeiXin/GetOpenId');
        return this.get<string>(url, { code });
    }

    /**
     * 通过 OpenId 登录
     * @param code 用于获取 OpenId 的 code
     * 
     */
    login(code: string): Promise<LoginResult | { SellerId: string }> {
        let url = this.url('Member/Login');
        return this.postByJson<LoginResult | { SellerId: string }>(url, { code }).then(result => {
            //token 为空表示 openid 没有绑定
            if ((result as LoginResult).token != null) {
                WeiXinService.token.value = (result as LoginResult).token;
            }
            return result;
        });
    }
    bind(code: string) {
        let url = this.url('Member/Bind');
        return this.put<{ OpenId }>(url, { code });
    }
    unbind(code: string) {
        let url = this.url('Member/Unbind');
        return this.put<any>(url, { code });
    }
}


export default new WeiXinService();